import React, { useState, useEffect } from "react";
import { View, StyleSheet, Dimensions, Text } from "react-native";
import { Tab, TabView } from "@rneui/themed";
import { useSelector, useDispatch } from "react-redux";
import IconNavBar from '@/components/IconNavBar'
import { sectokenCommonCenterProps } from '@/config/navigatorProps'
import CommonContext from '@/utils/createContext'
import QueueList from './components/QueueList'
import HistoryList from './components/HistoryList'
import Loading from "@/components/LoadingModal";
import api from '@/request/api';
import { formatHistoryData } from "@/utils/util";

const { width, scale } = Dimensions.get('window')
const ratio = width * scale / 1080

const TransientScreen = (props) => {

    const dispatch = useDispatch();
    const [tabIndex, setTabIndex] = useState(0);
    const [loadingVisible, setLoadingVisible] = useState(false)
    const [historyNext, setHistoryNext] = useState('');
    const [queuedNext, setQueuedNext] = useState('');
    const selectedSafeWallet = useSelector((state) => state.sectokenMainReducer.selectedSafeWallet);
    const safeQueueList = useSelector((state) => state.sectokenMainReducer.safeQueueList);
    const safeHistoryList = useSelector((state) => state.sectokenMainReducer.safeHistoryList);

    useEffect(() => {
        if (selectedSafeWallet && selectedSafeWallet.address) {
            getPageData()
        }
    }, [])

    const getPageData = () => {
        setLoadingVisible(true)
        setTimeout(async () => {
            let res1 = await api.get_safe_queue(selectedSafeWallet.address)
            setQueuedNext(res1.next)
            dispatch({ type: "setSafeQueueList", value: res1 && res1.results })
            let res2 = await api.get_safe_history(selectedSafeWallet.address)
            setHistoryNext(res2.next)
            if (res2 && res2.results?.length > 0) {
                const result = formatHistoryData(res2.results)
                dispatch({ type: "setSafeHistoryList", value: result })
            }
            setLoadingVisible(false)
        }, 100);
    }

    const handlePressLeft = () => {
        props.navigation.goBack()
    }

    const handlePressItem = (txId, type) => {
        let name
        switch (type) {
            case 'general':
                name = 'safe-general-detail'
                break;
            case 'rejection':
                name = 'safe-rejection-detail'
                break;
            case 'receive':
                name = 'safe-receive-detail'
                break;
        }
        props.navigation.navigate({
            name,
            params: {
                txId
            }
        })
    }

    const handlePressCreation = (txInfo) => {
        dispatch({ type: "setTranscationDetail", value: txInfo });
        props.navigation.navigate('safe-creation-detail')
    }

    const loadMore = (type) => {
        if (selectedSafeWallet && selectedSafeWallet.address) {
            switch (type) {
                case 'queued':
                    if (queuedNext) {
                        setLoadingVisible(true)
                        setTimeout(async () => {
                            let result = await api.axios_get(`https://${queuedNext}`)
                            setQueuedNext(result.next)
                            let list = [].concat(safeQueueList).concat(result?.results || [])
                            dispatch({ type: "setSafeQueueList", value: [...list] })
                            setLoadingVisible(false)
                        }, 100);
                    }
                    break;
                case 'history':
                    if (historyNext) {
                        setLoadingVisible(true)
                        setTimeout(async () => {
                            let result = await api.axios_get(`https://${historyNext}`)
                            setHistoryNext(result.next)
                            if (result && result.results?.length > 0) {
                                const data = formatHistoryData(result.results)
                                let list = [].concat(safeHistoryList).concat(data)
                                dispatch({ type: "setSafeHistoryList", value: [...list] })
                            }
                            setLoadingVisible(false)
                        }, 100);
                    }
                    break;
            }
        }
    }

    return (
        <View style={styles.container}>
            <IconNavBar {...props} {...sectokenCommonCenterProps} {...{ title: 'Transactions' }} handlePressLeft={handlePressLeft} />
            <View style={styles.bodyContent}>
                <View style={{ flex: 1 }}>
                    <Tab value={tabIndex} onChange={(e) => setTabIndex(e)} indicatorStyle={{ backgroundColor: '#5757F9' }}>
                        <Tab.Item
                            containerStyle={{ backgroundColor: '#F7F7F7', height: 44 * ratio }}
                            buttonStyle={{ height: 44 * ratio }}
                            title={
                                <Text style={{ ...styles.title1, color: tabIndex == 0 ? '#0A6EEB' : '#2C2C2C' }}>
                                    QUEUE
                                </Text>}>
                        </Tab.Item>
                        <Tab.Item
                            containerStyle={{ backgroundColor: '#F7F7F7', height: 44 * ratio }}
                            buttonStyle={{ height: 44 * ratio }}
                            title={
                                <Text style={{ ...styles.title1, color: tabIndex == 1 ? '#0A6EEB' : '#2C2C2C' }}>
                                    HISTORY
                                </Text>}>
                        </Tab.Item>
                    </Tab>
                    <TabView value={tabIndex} onChange={(e) => setTabIndex(e)} animationType="spring">
                        <TabView.Item style={{ flex: 1 }}>
                            <CommonContext.Provider value={{ safeQueueList, handlePressItem, loadMore }}>
                                <QueueList />
                            </CommonContext.Provider>
                        </TabView.Item>
                        <TabView.Item style={{ flex: 1 }}>
                            <CommonContext.Provider value={{ safeHistoryList, handlePressItem, handlePressCreation, loadMore }}>
                                <HistoryList />
                            </CommonContext.Provider>
                        </TabView.Item>
                    </TabView>
                </View>
            </View>
            {loadingVisible && <Loading visible={loadingVisible} />}
        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#FFFFFF'
    },
    bodyContent: {
        flex: 1
    },
    title1: {
        fontSize: 14,
        fontFamily: 'SourceHanSansCN-Medium, SourceHanSansCN',
        fontWeight: '500',
        color: '#2C2C2C',
        lineHeight: 21
    }
})
export default TransientScreen